﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://www.codeplex.com/EmlenMud
// Experimental/Exploratory
#if USE_FLEE
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using BrainTechLLC.ThreadSafeObjects;
using Ciloci.Flee;
using Ciloci;

namespace BrainTechLLC
{
    public static class FleeExtensions
    {
        public static readonly ThreadSafeLookup<string, IGenericExpression<object>> CompiledExpressions = new ThreadSafeLookup<string, IGenericExpression<object>>();

        // = ExpressionFactory.CreateGeneric(Of Double)("x+2*y", MyContext)
        public static T Evaluate<T>(this VariableContainer variables, string eval)
        {
            T returnValue;
            IGenericExpression<object> expression;
            ExpressionContext context = new ExpressionContext(variables);
            eval = variables.EvalString(eval);

            // Import math so we have access to its functions in expressions
            context.Imports.AddType(typeof(Math));
            context.Imports.AddType(typeof(Convert));

            if (!CompiledExpressions.TryGetValue(eval, out expression))
            {                
                expression = context.CompileGeneric<object>(eval);
                CompiledExpressions.AddOrSet(eval, expression);
            }

            lock (expression)
            {
                expression.Owner = variables;
                returnValue = (T)Convert.ChangeType(expression.Evaluate(), typeof(T));
            }

            return returnValue;
        }
    }
}
#endif